package net.wang.concurrency.test.count;

import lombok.extern.slf4j.Slf4j;
import net.wang.concurrency.annoations.NotThreadSafe;
import net.wang.concurrency.annoations.ThreadSafe;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressWarnings("ALL")
@Slf4j
@ThreadSafe
public class CountTestAtomic {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    //AtomicInteger AtomicLong LongAdder
   // AtomicLong 与 LongAdder的区别时在检查数据与期望值相等时，AtomicLong一个单元遍历检查，LongAdder是将所有的值分组检查。
    public static AtomicInteger count = new AtomicInteger(0);

    @Test
    public void atomicIntegerTest() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    addInteger();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info("exception : {}", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count = {}", count);
    }

    public  void addInteger() {
        count.incrementAndGet();
        //count.getAndIncrement();
    }

}
